import React, { useState, useEffect } from "react";
import { Menu, Layout } from "antd";
import { useNavigate, useLocation } from "react-router";
import "./index.css";
import { UserOutlined, VideoCameraOutlined } from "@ant-design/icons";
import axios from "axios";
import { connect } from "react-redux";
const { Sider } = Layout;
const SubMenu = Menu.SubMenu;

const mapStateToProps = ({ CollapsedReducer: { isCollapsed } }) => {
  return {
    isCollapsed,
  };
};

export default connect(mapStateToProps)(function SideMenu(props) {
  let navigate = useNavigate();
  // const [collapsed, setCollapsed] = useState(false);
  const [menuList, setmenuList] = useState([]);
  const checkPagePermission = (item) => {
    return item.pagepermisson && rights.includes(item.key);
  };

  const renderMenu = (menuList) => {
    return menuList.map((item) => {
      if (item.children?.length > 0 && checkPagePermission(item)) {
        return (
          <SubMenu key={item.key} icon={<UserOutlined />} title={item.title}>
            {renderMenu(item.children)}
          </SubMenu>
        );
      }
      return (
        checkPagePermission(item) && (
          <Menu.Item
            key={item.key}
            icon={<VideoCameraOutlined />}
            onClick={() => navigate(item.key)}
          >
            {item.title}
          </Menu.Item>
        )
      );
    });
  };
  useEffect(() => {
    axios.get("/rights?_embed=children").then((res) => {
      console.log(res.data);
      setmenuList(res.data);
    });
  }, []);

  let location = useLocation();
  const selectKeys = [location.pathname]; // ex: ['/home']
  const openKeys = ["/" + location.pathname.split("/")[1]];
  const {
    role: { rights },
  } = JSON.parse(localStorage.getItem("token"));
  return (
    <Sider trigger={null} collapsible collapsed={props.isCollapsed}>
      <div style={{ display: "flex", height: "100%", flexDirection: "Column" }}>
        <div className="logo">全球新闻发布管理系统</div>
        <div style={{ flex: 1, overflow: "auto" }}>
          <Menu
            theme="dark"
            mode="inline"
            defaultSelectedKeys={openKeys}
            selectedKeys={selectKeys}
          >
            {renderMenu(menuList)}
          </Menu>
        </div>
      </div>
    </Sider>
  );
});
